import { ApiService } from './api.service';
import { AudioService } from './audio.service';

interface TranslationResponse {
  translation: string;
  detected_language: string;
}

export class TranslatorService {
  static async translate(
    text: string,
    sourceLanguage: string,
    targetLanguage: string
  ): Promise<TranslationResponse> {
    try {
      return await ApiService.post<TranslationResponse>('translate', {
        text,
        source_language: sourceLanguage,
        target_language: targetLanguage,
      });
    } catch (error) {
      console.error('Translation Error:', error);
      throw error;
    }
  }

  static async textToSpeech(text: string, language: string = 'zh'): Promise<void> {
    try {
      const response = await ApiService.post('speech', {
        text,
        language,
      }, { responseType: 'arraybuffer' });

      const blob = new Blob([response], { type: 'audio/mpeg' });
      const url = URL.createObjectURL(blob);
      
      const audio = await AudioService.playAudio(url);

      audio.onended = () => {
        URL.revokeObjectURL(url);
      };
    } catch (error) {
      console.error('Speech Error:', error);
      throw error;
    }
  }
}